<?php

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.application.component.model');

class SyncrModelProcess extends JModel
{	
	var $_data		= null;
	var $_processId	= null;

	function __construct() {
		parent::__construct();
		
		$this->_processId = JRequest::getInt('processId', 0);
		
		// new class
		$evl = new evolveLibrary;
		
		// load some evl stuff
		$this->_log = $evl->loadHelper('log');
		$this->_htmlparser = $evl->loadHelper('htmlparser');
	}
	
	public function getData()
	{	
		// Lets load the content if it doesn't already exist
		if (empty($this->_data))
		{		
			// get item
			$this->_data = $this->_getItem();
			
			$params = &JComponentHelper::getParams( 'com_syncr' );
			
			// process item | copy image param
			if ($params->get('imagecopy')) {
				if ($this->_processImage()) {
					$this->_log->simpleLog('process.php/_getData: processImage failed', 'syncr');
				}
			}
			$this->_log->simpleLog('process.php/_getData: '.$params->get('imagecopy').'xxx', 'syncr');
			
			// save to database
			if (!$params->get('hold')) {
				if (!$this->storeContent()) {
					$this->_log->simpleLog('process.php/_getData: storeContent failed', 'syncr');
					JError::raiseError(500, JText::_('Could not post content'));
				}
			} else {
				if (!$this->storeHold()) {
					$this->_log->simpleLog('process.php/_getData: Hold failed', 'syncr');
					JError::raiseError(500, JText::_('Could not post content'));
				}
			}	
		}
		
		return;
	}
	
	private function _getItem()
	{
		$db =& JFactory::getDBO();
		
		$query = 'SELECT process_id'
			   .', data'
			   .', category'
			   .' FROM #__syncr_content'
			   .' WHERE process_id = '.$this->_processId;
			   ;
		$db->setQuery($query);
		
		return $db->loadObject();
	}
	
	public function storeContent()
	{
		$row =& $this->getTable('com_content', 'Table');
		
		$json = json_decode($this->_data->data);
		
		$post['title'] = $json->title;
		$post['alias'] = $json->alias;
		$post['introtext'] = $json->introtext;
		$post['fulltext'] = $json->fulltext;
		$post['state'] = $json->state;
		$post['created'] = $json->created;
		$post['created_by'] = $json->created_by;
		$post['created_by_alias'] = $json->created_by_alias;
		$post['modified'] = $json->modified;
		$post['modified_by'] = $json->modified_by;
		$post['publish_up'] = $json->publish_up;
		$post['publish_down'] = $json->publish_down;
		$post['attribs'] = $json->attribs;
		$post['version'] = $json->version;
		$post['metakey'] = $json->metakey;
		$post['metadesc'] = $json->metadesc;
		$post['access'] = $json->access;
		$post['metadata'] = $json->metadata;
		
		// we need go add sectionId to item
		$post['sectionid'] = $this->_getSection($this->_data->category);
		
		$post['catid'] = $this->_data->category;
		
		if (!$row->bind($post)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		if (!$row->store()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		return true;
	}
	
	private function _getSection($catid)
	{
		$db = &JFactory::getDBO();
		
		$query = 'SELECT section'
			   .' FROM #__categories'
			   .' WHERE id = '.$catid
			   ;
		
		$db->setQuery($query);
		return $db->loadResult();
	}
	
	private function _processImage()
	{
		jimport('joomla.filesystem.file');
					
		// images stored in /images/stories/weburl.com/path/to/image.ext
		
		$data = json_decode($this->_data->data);
		
		// get image from fulltext/introtext
		$html[] = $this->_htmlparser->str_get_html($data->introtext);
		$html[] = $this->_htmlparser->str_get_html($data->fulltext);
		
		$image_path = null;
		foreach($html as $html) {
			foreach($html->find('img') as $element) {
				$image_path[] = $element->src;
			}
		}
		
		if (!$image_path) {
			return;
		}
		
		foreach($image_path as $image) {
			$isNew = false;
			$exists = false;
			
			// create path
			$path_parts = pathinfo($image);
			$path_dirname = $path_parts['dirname'];
			
			// remove http://
			$path_dirname = ltrim($path_dirname, 'http://');
			
			// final path
			$path_parts['dirname'] = JPATH_ROOT.'/images/stories/'.$path_dirname;
			
			JFolder::create($path_parts['dirname'], 0775);
		
			// check if folder heirarchy exists
			if (!JFolder::exists($path_parts['dirname'])) {
				// create folder heirarchy
				JFolder::create($path_parts['dirname'], 0775);
				
				// skip image check if creating
				$isNew = true;
			}
			
			// existing folder only
			if (!$isNew) {
			
				// check if image exists
				if (JFile::exists($path_parts['dirname'].DS.$path_parts['basename'])) {
					// skip curl if exists
					$exists = true;
				}
			}
			
			// new image only
			if (!$exists) {
				// download image
				$ch = curl_init ($image);
				curl_setopt($ch, CURLOPT_HEADER, 0);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
				$rawdata=curl_exec ($ch);
				curl_close ($ch);
				
				// save image to folder
				$fp = fopen($path_parts['dirname'].DS.$path_parts['basename'], 'w');
				fwrite($fp, $rawdata); 
				fclose($fp);
			}
			
			// repath text
			$data->introtext = str_replace($image, $path_parts['dirname'].DS.$path_parts['basename'], $data->introtext);
			$data->fulltext = str_replace($image_path, $path_parts['dirname'].DS.$path_parts['basename'], $data->fulltext);
		}
		
		$this->_data->data = json_encode($data);
		return;		
	}
	
	public function storeHold()
	{
		$row =& $this->getTable('hold', 'Table');
				
		if (!$row->bind($this->_data)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		if (!$row->store($this->_data)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		return true;
	}
}